<?php
define("IS_MAIN", true);
require "./modules/set.php";
$pd = dirname(__DIR__) . "/projects";
$projects_id = scandir($pd);
unset($projects_id[array_search(".", $projects_id)]);
unset($projects_id[array_search("..", $projects_id)]);
// echo json_encode($projects_id);

header("Content-Type: application/json;charset=utf8");

if ($_SERVER["REQUEST_METHOD"] != "GET") {
    echo '{"code":"error",msg:"Method Not Allowed"}';
    exit;
}
$search = "";
if (isset($_COOKIE["htqw_share_search_keyword"])) {
    $search = $_COOKIE["htqw_share_search_keyword"];
}

$projects = [];

$conn = mysqli_connect($app["sql"]["host"], $app["sql"]["user"], $app["sql"]["password"], $app["sql"]["dbname"], $app["sql"]["port"]);

function passage($pro)
{
    global $conn;
    if (file_get_contents("../projects/" . $pro . "/ban.txt") == "true") {
        return false;
    }
    $author_id = file_get_contents("../projects/" . $pro . "/author.txt");
    $id = basename("../projects/" . $pro);
    $name = file_get_contents("../projects/" . $pro . "/name.txt");
    $describe = file_get_contents("../projects/" . $pro . "/describe.txt");
    $time = file_get_contents("../projects/" . $pro . "/time.txt");
    $cmd = $conn->query("select name,email,op from users where id='" . $author_id . "';");
    if (!$cmd) {
        return false;
    }
    $res = $cmd->fetch_assoc();

    return [
        "author" => [
            "id" => $author_id,
            "name" => $res["name"],
            "email" => $res["email"],
            "op" => $res["op"]
        ],
        "project" => [
            "id" => $id,
            "name" => $name,
            "describe" => $describe,
            "time" => $time,
            "pic" => "projects/" . $id . "/pic.png",
            "code" => "projects/" . $id . "/code.zip"
        ]
    ];
}

if ($search == "") {
    foreach ($projects_id as $key => $pro) {
        $proj = passage($pro);
        if ($proj) {
            $projects["p" . $proj["project"]["id"]] = $proj;
        }
    }
} else {
    foreach ($projects_id as $key => $pro) {
        $proj = passage($pro);
        if (($proj) && (strpos($proj["project"]["name"], urldecode($search)) !== false)) {

            $projects["p" . $proj["project"]["id"]] = $proj;
        }
    }
}

echo json_encode((object) $projects);
